package frontend.pages.login;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.value.ValueMap;

import frontend.components.language.LanguagePanel;
import frontend.core.TimeTrackingWebSession;
import org.wicketstuff.annotation.mount.MountPath;

@MountPath("login")
public class LoginPage extends WebPage {

	public LoginPage() {
		SignInForm signInForm = new SignInForm("loginForm");
		signInForm.add(new FeedbackPanel("feedback"));
		signInForm.add(new LanguagePanel("languagePanel"));
		add(signInForm);
	}

	public final class SignInForm extends Form<Void> {
		private static final String USERNAME = "username";
		private static final String PASSWORD = "password";

		private final ValueMap properties = new ValueMap();

		public SignInForm(final String id) {
			super(id);

            add(new Label("usernameLabel", new ResourceModel("pages.login.username")));
			add(new TextField<String>(USERNAME, new PropertyModel<String>(properties, USERNAME)));
            add(new Label("passwordLabel", new ResourceModel("pages.login.password")));
			add(new PasswordTextField(PASSWORD, new PropertyModel<String>(properties, PASSWORD)));
		}

		@Override
		public final void onSubmit() {
			TimeTrackingWebSession session = getMySession();

			if (session.signIn(getUsername(), getPassword())) {
				if (!continueToOriginalDestination()) {
					setResponsePage(getApplication().getHomePage());
				}
			} else {
				String errorMassage = getString("pages.login.error");
				error(errorMassage);
			}
		}

		private String getPassword() {
			return properties.getString(PASSWORD);
		}

		private String getUsername() {
			return properties.getString(USERNAME);
		}

		private TimeTrackingWebSession getMySession() {
			return (TimeTrackingWebSession) getSession();
		}
	}
}
